package com.hp.tiger.chapter18;

import java.util.LinkedList;

/**
 * @author XavierDong
 **/
public class ActivationQueue {

    private static final int MAX_METHOD_REQUEST_QUEUE_SIZE = 100;

    private final LinkedList<MethodRequest> methodRequests;

    public ActivationQueue() {
        this.methodRequests = new LinkedList<>();
    }


    public synchronized void put(MethodRequest request) {
        while (methodRequests.size() >= MAX_METHOD_REQUEST_QUEUE_SIZE) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        this.methodRequests.addLast(request);
        this.notifyAll();
    }


    public synchronized MethodRequest take() {
        while (methodRequests.isEmpty()) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        MethodRequest methodRequest = methodRequests.removeFirst();
        this.notifyAll();
        return methodRequest;
    }
}
